<?php namespace App\Core\Service\Services;

use DB;
use App\Core\Exceptions\InputError;

trait Updater{
    
    public $updateFields = [];
    public $updateData = [];
    public $updateModel;
    
    public function update(){
        try {
            $this->fireEvent('updateGeneratingFeilds');
            $this->updateGenerateFeilds();
            $this->fireEvent('updateGeneratedFeilds');
            $this->updateGenerateData();
            $this->fireEvent('updateGeneratedData');
            $this->updateValidate();
            if(!$this->validateRes['status']){
                $error = array_shift($this->validateRes['errors']);
                return $this->inputError('数据格式有误。字段'.$error[0].$error[1]);
            }
            $this->getRepository()->addCriteria($this->getIndexCriteria());
            $this->fireEvent('updateBeforeSave');
            $this->updateSaveData();
            $this->fireEvent('createAfterSave');
            return $this->success();
		} catch (\Exception $ex) {
            if($ex instanceof InputError){
                return $this->inputError($ex->getMessage());
            }
            return $this->sysError($ex);
		}
    }
    
    public function updateGenerateFeilds(){
        $this->updateFields = $this->getMeta()->getUpdateFields();
        return $this;
    }
    
    protected function updateGenerateData(){
        $this->updateData = $this->getMeta()->getData($this->updateFields);
        return $this;
    }
    
    protected function updateValidate(){
        $rules = $this->getMeta()->getRules($this->updateFields);
        $this->validateRes = $this->validator->validate($this->updateData, $rules);
    }
    
    protected function updateSaveData(){
        DB::beginTransaction();
        try {
            $this->fireEvent('updateSaving');
            $this->updateModel = $this->getRepository()->update($this->updateData)->first();
            $this->fireEvent('updateSaved');
            DB::commit();
		} catch (\Exception $ex) {
            DB::rollBack();
			throw $ex;
        }
    }
}